import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/product_equhisdata_odoo_api.dart';
import 'package:flutter_admin/api/odoo/product_plateconsumption_odoo_api.dart';
import 'package:flutter_admin/models/odoo/product_equhisdata.dart';
import 'package:flutter_admin/models/odoo/product_plateconsumption.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import '../../../generated/l10n.dart';

class ProductEquhisdataChart extends StatefulWidget {
  ProductEquhisdataChart();

  @override
  _ProductEquhisdataChartState createState() => _ProductEquhisdataChartState();
}

class _ProductEquhisdataChartState extends State<ProductEquhisdataChart> {
  ProductEquhisdata productEquhisdata = ProductEquhisdata();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  List<ProductEquhisdata> _productEquhisdataList = [];
  //设备名称
  List<SelectOptionVO> devList = [];

  DateFormat format = DateFormat('yyyy-MM-dd HH:mm:ss');

  bool flag = false;

  late ZoomPanBehavior _zoomPanBehavior;

  @override
  void initState() {
    super.initState();
    productEquhisdata.histimeStart = Utils.getDate()+" 00:00:00";
    productEquhisdata.histimeEnd = Utils.getDate()+" 23:59:59";
    _zoomPanBehavior = ZoomPanBehavior(
      enablePinching: true,
      enableMouseWheelZooming : true,
      zoomMode: ZoomMode.x,
      enablePanning: true,
    );
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async{
    //设备名称
    devList = await DynamicDataApi.getModelSelect(
        model: 'base.productionstation',
        tag: 'epu_id',
        name: 'stationname',
        key: 'isproduction',
        val: '1'
    );
    setState(() { });
  }

  _reset() {
    productEquhisdata = ProductEquhisdata();
    productEquhisdata.histimeStart = Utils.getDate()+" 00:00:00";
    productEquhisdata.histimeEnd = Utils.getDate()+" 23:59:59";
    formKey.currentState!.reset();
    _productEquhisdataList= [];
    setState(() {});
    // _loadData();
  }

  _query() {
    if(!formKey.currentState!.validate()){
      return ;
    }
    formKey.currentState?.save();
    // tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ProductEquhisdataOdooApi.findAll(
        data:{"domainList":productEquhisdata.toChartDomainList()});
    if(responseBodyApi.success!){
      _productEquhisdataList = responseBodyApi.data != null ? responseBodyApi.data
          .map<ProductEquhisdata>((e) => ProductEquhisdata.fromMap(e))
          .toList()
        : [];
      if(responseBodyApi.data.length != 0){
        flag = responseBodyApi.data[0]["product_type"] == "BJSC";
      }
      setState(() {});
    }
  }

  List<LineSeries<ProductEquhisdata, String>> _getSeries() {
    return <LineSeries<ProductEquhisdata, String>>[
      LineSeries<ProductEquhisdata, String>(
        name: "开关机信号",
        dataSource: _productEquhisdataList,
        pointColorMapper:(ProductEquhisdata productEquhisdata, _) => productEquhisdata.timevalue == "1"?Colors.greenAccent:Colors.redAccent,
        xValueMapper: (ProductEquhisdata productEquhisdata, _) => productEquhisdata.histime,
        yValueMapper: (ProductEquhisdata productEquhisdata, _) => double.parse(productEquhisdata.timevalue!),
        markerSettings: MarkerSettings(isVisible: true),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    var buttonBar = CryButtonBar(
      children: [
        CryButton(
          label: S.of(context).query,
          iconData: Icons.search,
          padding: EdgeInsets.only(left: 20),
          onPressed: () => _query(),
        ),
        CryButton(
          label: S.of(context).reset,
          iconData: Icons.refresh,
          padding: EdgeInsets.only(left: 20),
          onPressed: () => _reset(),
        ),
      ],
    );
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          DateTimeSelect(
            context,
            width: 280,
            label: '采集开始日期',
            value: productEquhisdata.histimeStart,
            lastDate: productEquhisdata.histimeEnd!=''&&productEquhisdata.histimeEnd!=null?format.parse(productEquhisdata.histimeEnd!):null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productEquhisdata.histimeStart = v;
              setState(() {});
            },
            onSaved: (v) {
              productEquhisdata.histimeStart = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 280,
            label: '采集结束时间',
            value: productEquhisdata.histimeEnd,
            firstDate: productEquhisdata.histimeStart!=''&&productEquhisdata.histimeStart!=null?format.parse(productEquhisdata.histimeStart!):null,
            onDateChange: (v) {
              formKey.currentState?.save();
              productEquhisdata.histimeEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              productEquhisdata.histimeEnd = v;
            },
          ),
          CrySelect(
            width: 350,
            label: '设备名称',
            dataList: devList,
            value: productEquhisdata.devid,
            onSaved: (v) => { productEquhisdata.devid = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          Padding(padding: EdgeInsets.only(top: 17),child: buttonBar,)
        ],
      ),
    );
    var chart = SfCartesianChart(
      zoomPanBehavior: _zoomPanBehavior,
      title: ChartTitle(
          text: flag?"A相电流":'开关机信号(0:关机;1:开机)',
          // backgroundColor: Colors.lightGreen,
          // borderColor: Colors.blue,
          // borderWidth: 2,
          // // Aligns the chart title to left
          // alignment: ChartAlignment.near,
          // textStyle: TextStyle(
          //   color: Colors.red,
          //   fontFamily: 'Roboto',
          //   fontStyle: FontStyle.italic,
          //   fontSize: 14,
          // )
      ),
      plotAreaBorderWidth: 0,
      enableAxisAnimation: true,
      // legend: Legend(isVisible: true),
      primaryXAxis: CategoryAxis(
        labelRotation: -45,
        majorGridLines: MajorGridLines(width: 0),
        labelPlacement: LabelPlacement.onTicks),
      primaryYAxis: flag?NumericAxis(
        labelFormat: "{value}A",
      ):NumericAxis(
          minimum: 0,
          maximum: 1,
          interval: 1
      ),
      series: _getSeries(),
      tooltipBehavior: TooltipBehavior(enable: true),
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text("设备趋势图"),
      ),
      body: Column(
        children: [
          form,
          Expanded(child:
          _productEquhisdataList.length!=0?
          chart:Container(alignment: Alignment.center,
          child: Text("没有获取到采集数据",style: TextStyle(fontSize: 35,color: Colors.redAccent),),)),
        ],
      ),
    );
    return result;
    // return result;
  }
}